package com.lm.upms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lm.upms.api.entity.SysRole;
import com.lm.upms.api.entity.SysRoleMenu;
import com.lm.upms.mapper.SysRoleMapper;
import com.lm.upms.service.SysRoleMenuService;
import com.lm.upms.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色
 *
 * @author lm
 * @date
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public IPage<List<SysRole>> getListPageBy(Page page, SysRole sysRole) {
        return this.baseMapper.getListPageBy(page, sysRole);
    }

    /**
     * 通过用户ID查询角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List findRolesByUserId(Integer userId) {
        return this.baseMapper.listRolesByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertRole(SysRole sysRole) {
        // 新增角色信息
        this.baseMapper.insert(sysRole);
        return sysRoleMenuService.saveRoleMenus(sysRole.getRoleId(), sysRole.getMenuIds());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateRole(SysRole sysRole) {
        // 修改角色信息
        this.baseMapper.updateById(sysRole);
        // 删除角色与菜单关联
        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, sysRole.getRoleId()));
        return sysRoleMenuService.saveRoleMenus(sysRole.getRoleId(), sysRole.getMenuIds());
    }

    /**
     * 通过角色ID，删除角色,并清空角色菜单缓存
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean removeRoleById(String ids) {
        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>update().lambda().eq(SysRoleMenu::getRoleId, ids));
        return this.removeById(ids);
    }

}